<template>
  <div class="page">
    <s-header :name="'开工申请'" :back="'/government/home'"></s-header>
    <van-form ref="dataForm" class="start-apply">
      <div class="card-box">
        <div class="card-item">
          <div class="card-header">申请选择</div>
          <van-divider />
          <div class="card-body card-body-nop">
            <custom-select
              :selectId="applyBaseId"
              :columns="buildApplyColumns"
              :otherOrg="otherOrg"
              :option="{ label: 'applyOrderNo', value: 'id' }"
              :rules="dataRule.applyBaseId"
              :disabled="disabledSelect"
              required
              label="建房申请记录"
              label-width="100px"
              @getValue="getValue"
            ></custom-select>
            <van-search v-model="searchMan" show-action label="" placeholder="请输入工匠姓名查询">
              <template #action>
                <div @click="handleSearchName">搜索</div>
              </template>
            </van-search>
            <div class="field-item" v-show="craftsmanList.length > 0">
              <label class="field-label">选择工匠：</label>
              <div class="field-value">
                <div class="tag-group">
                  <span v-for="(item, index) in craftsmanList" :key="index" class="tag">
                    <span>{{ item.name }}</span>
                    <van-icon name="cross" class="tag-close" @click="handleCloseTag(index)" />
                  </span>
                </div>
              </div>
            </div>
            <div v-show="craftsmanOptions.length > 0" class="craftsman-group">
              <div class="cell-box">
                <van-checkbox-group v-model="craftsmanId" ref="checkboxGroup" icon-size="15px" @change="selectCraftsman">
                  <div v-for="(item, index) in craftsmanOptions" :key="index" class="cell">
                    <van-checkbox :name="item.id"> {{ item.name }}（{{ item.address }}） </van-checkbox>
                  </div>
                </van-checkbox-group>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="card-box">
        <div class="card-item">
          <div class="card-header title-required">申请内容</div>
          <van-divider />
          <div class="card-body">
            <van-field
              v-model="applyContent"
              :rules="dataRule.applyContent"
              rows="3"
              autosize
              label=""
              type="textarea"
              maxlength="100"
              placeholder="申请划定宅基地用地范围"
              show-word-limit
              class="noPadding"
            />
          </div>
        </div>
      </div>
      <div class="card-box">
        <div class="card-item">
          <div class="card-header title-required">现场图片</div>
          <van-divider />
          <div class="card-body">
            <image-upload v-model:value="pictures" fileType="A15" @uploadBack="uploadBack"></image-upload>
          </div>
        </div>
      </div>
      <div class="card-box">
        <div class="card-item">
          <div class="card-header">应提供材料</div>
          <van-divider style="margin-bottom: 10px" />
          <div class="card-body">
            <div v-for="(item, index) in providedMaterialsList" :key="index" class="file-title">
              <div class="title title-required">{{ item.title }}</div>
              <image-upload
                v-model:value="item.fileList"
                :maxCount="10"
                :typeIndex="index"
                :fileType="item.type"
                @uploadBack="uploadBack"
              ></image-upload>
            </div>
          </div>
        </div>
      </div>
      <div class="card-box">
        <div class="card-item">
          <div class="card-header">其他相关材料</div>
          <van-divider />
          <div class="card-body">
            <image-upload v-model:value="otherMaterials" :maxCount="10" fileType="A17" @uploadBack="uploadBack"></image-upload>
          </div>
        </div>
      </div>

      <div class="btn-group">
        <van-button type="button" class="cus-btn btn-default" :loading="isCommit" @click="handleSave">保存</van-button>
        <van-button type="button" class="cus-btn btn-primary" :loading="isCommit" @click="handleSubmit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { reactive, toRefs, ref, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { Toast } from 'vant'
import ImageUpload from '@/components/ImageUpload'
import sHeader from '@/components/SimpleHeader'
import { saveLoitBuildStartApply, getBuildApply, queryCraftsman } from '@/service/start-apply'
import { getStartApplyDetail } from '@/service/home'
export default {
  components: {
    sHeader,
    ImageUpload,
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()
    const dataForm = ref(null)
    const state = reactive({
      isCommit: false,
      fileList: [],
      applyBaseId: null,
      otherOrg: ['applyName', 'applyTime'],
      disabledSelect: false,
      applyContent: '',
      startId: '',
      buildApplyColumns: [],
      selectValue: [],
      searchMan: '',
      craftsmanId: [],
      craftsmanList: [],
      craftsmanOptions: [],
      pictures: [],
      // providedMaterials: [],
      otherMaterials: [],
      allFileList: [],
      providedMaterialsList: [
        { title: '施工合同', fileList: [], type: 'A16' },
        { title: '农房设计图纸', fileList: [], type: 'A61' },
        { title: '承揽施工的企业资质/农村建筑工匠负责人身份证复印件', fileList: [], type: 'A62' },
        { title: '农村建筑工匠培训证复印件', fileList: [], type: 'A63' },
        { title: '农民工工伤保险单复印件', fileList: [], type: 'A64' },
      ],
      fileAccept: '.rar,.zip,.doc,.docx,.pdf,.jpg,.jpeg,.png,.xls,.xlxs',
      dataRule: {
        applyBaseId: [{ required: true, message: '请选择建房申请记录', trigger: 'onChange' }],
        applyContent: [{ required: true, message: '请输入申请内容', trigger: 'onBlur' }],
      },
    })

    // 获取建房申请记录
    getBuildApply().then((res) => {
      state.buildApplyColumns = res.body.obj || []
    })

    store.dispatch('getFileServerPrefix')

    onMounted(async () => {
      const { id } = route.query
      if (id) {
        getStartApplyDetail(id).then((res) => {
          const loitBuildStartApply = res.data.loitBuildStartApply
          if (loitBuildStartApply) {
            const { id, applyOrderNo, applyName, applyTime } = res.data.buildApplyBase
            state.buildApplyColumns.push({
              id: id,
              applyOrderNo: applyOrderNo,
              applyName: applyName,
              applyTime: applyTime,
            })
            state.disabledSelect = true
          }
          const { files, photos, others, applyBaseId, applyContent } = loitBuildStartApply
          if (files && files.length > 0) {
            files.forEach((item) => {
              if (item.url.indexOf(fileServerPrefix.value) === -1) {
                item.filePath = item.url
                item.url = fileServerPrefix.value + item.url
              }
            })
          }
          if (photos && photos.length > 0) {
            photos.forEach((item) => {
              if (item.url.indexOf(fileServerPrefix.value) === -1) {
                item.filePath = item.url
                item.url = fileServerPrefix.value + item.url
              }
            })
          }
          if (others && others.length > 0) {
            others.forEach((item) => {
              if (item.url.indexOf(fileServerPrefix.value) === -1) {
                item.filePath = item.url
                item.url = fileServerPrefix.value + item.url
              }
            })
          }
          state.startId = loitBuildStartApply.id
          state.applyBaseId = applyBaseId
          state.craftsmanList = loitBuildStartApply.craftsmanInfos
          state.applyContent = applyContent
          state.pictures = photos

          files.forEach((atta) => {
            state.providedMaterialsList.forEach((mater) => {
              if (atta.type === mater.type) {
                mater.fileList.push(atta)
              }
            })
          })

          state.otherMaterials = others
        })
      }
    })

    // 文件上传后回调
    const uploadBack = (fileList, type) => {
      switch (type) {
        case 'A15':
          state.pictures = fileList
          break
        case 'A17':
          state.otherMaterials = fileList
          break
        default:
          state.providedMaterialsList.forEach((item) => {
            if (item.type === type) {
              item.fileList = fileList
            }
          })
          break
      }
    }

    // 查询工匠
    const handleSearchName = () => {
      if (state.searchMan) {
        queryCraftsman({ name: state.searchMan }).then((res) => {
          state.craftsmanOptions = res.data || []
          if (res.data && res.data.length === 0) {
            Toast('暂无该工匠信息')
          }
        })
      }
    }

    // 删除工匠
    const handleCloseTag = (index) => {
      state.craftsmanList.splice(index, 1)
    }
    // 选择工匠
    const selectCraftsman = (selectArr) => {
      let result = state.craftsmanOptions.filter((v) => selectArr.indexOf(v.id) > -1)

      let c = [...state.craftsmanList, ...result] //两个数组合并一个的简单方法
      let d = []
      let hash = {}
      d = c.reduce((item, next) => {
        hash[next.id] ? '' : (hash[next.id] = true && item.push(next))
        return item
      }, [])
      state.craftsmanList = d
    }

    // 获取建房申请记录id
    const getValue = (val) => {
      state.applyBaseId = val
    }

    const craftsmanConfirm = (val) => {
      state.selectValue = val
      let nameArr = []
      state.craftsmanOptions.forEach((man) => {
        val.forEach((item) => {
          if (man.value === item) {
            nameArr.push(man.name)
          }
        })
      })
      state.craftsmanId = nameArr.join(',')
    }

    const validateData = () => {
      if (state.craftsmanList.length === 0) {
        Toast.fail('请搜索工匠姓名选择工匠')
        return false
      }
      if (!state.pictures || state.pictures.length === 0) {
        Toast.fail(`请上传现场图片`)
        return false
      }
      for (let index = 0; index < state.providedMaterialsList.length; index++) {
        const item = state.providedMaterialsList[index]
        if (!item.fileList || item.fileList.length === 0) {
          Toast.fail(`请上传${item.title}`)
          return false
        }
      }
      return true
    }

    const handSendData = (isSubmit) => {
      return new Promise((resove, reject) => {
        let pictures = JSON.parse(JSON.stringify(state.pictures))
        let providedMaterials = []
        state.providedMaterialsList.forEach((item) => {
          providedMaterials = providedMaterials.concat(item.fileList)
        })
        let otherMaterials = JSON.parse(JSON.stringify(state.otherMaterials))
        pictures.forEach((item, index) => {
          item.sort = index
          item.url = item.filePath ? item.filePath : item.url
        })
        providedMaterials.forEach((item, index) => {
          item.sort = index
          item.url = item.filePath ? item.filePath : item.url
        })
        otherMaterials.forEach((item, index) => {
          item.sort = index
          item.url = item.filePath ? item.filePath : item.url
        })
        const craftsmanIds = state.craftsmanList.map((v) => v.id).join(',')
        let params = {
          applyBaseId: state.applyBaseId,
          applyContent: state.applyContent,
          attachInfoDTOList: [...pictures, ...providedMaterials, ...otherMaterials],
          craftsmanId: craftsmanIds,
          isSubmit: isSubmit,
          id: state.startId,
        }
        state.isCommit = true
        saveLoitBuildStartApply(params)
          .then((res) => {
            if (res.code == 100) {
              resove(true)
            }
            state.isCommit = false
          })
          .catch((err) => {
            state.isCommit = false
            reject(err)
          })
      })
    }

    // 保存
    const handleSave = () => {
      if (state.applyBaseId) {
        handSendData(false).then(() => {
          Toast.success('保存成功')
          setTimeout(() => {
            router.push({ path: '/government/record-apply/record-list', query: { applyType: 2 } })
          }, 500)
        })
      } else {
        Toast.fail('请选择建房申请记录')
      }
    }
    // 提交数据
    const handleSubmit = () => {
      dataForm.value.validate().then(() => {
        if (!validateData()) return

        handSendData(true).then(() => {
          Toast.success('提交成功')
          setTimeout(() => {
            router.push({
              name: 'GovernResultsPage',
              params: {
                stepList: JSON.stringify([
                  { title: '开工申请提交成功', desc: '您已成功提交开工申请，请等待相关部门现场审查，确定建房位置。', finishTime: '2021-12-03' },
                  { title: '等待审批通知', desc: '审批通过后，可以开始建房啦', finishTime: '' },
                  { title: '申请竣工', desc: '住宅建成后，在本平台首页申请竣工', finishTime: '' },
                ]),
                stepActive: 1,
                applyType: 2,
              },
            })
          }, 500)
        })
      })
    }

    const fileServerPrefix = computed(() => {
      return store.state.fileServerPrefix
    })

    return {
      dataForm,
      fileServerPrefix,
      ...toRefs(state),
      handleSave,
      handleSubmit,
      getValue,
      craftsmanConfirm,
      handleSearchName,
      handleCloseTag,
      selectCraftsman,
      uploadBack,
    }
  },
}
</script>

<style lang="less" scoped>
@import '@/common/style/mixin';
.start-apply {
  padding-top: 12px;
  .title-required::before {
    margin-right: 5px;
    color: var(--van-field-required-mark-color);
    content: '*';
  }
  .card-body {
    .file-title {
      line-height: 23px;
      font-size: 15px;
      font-weight: 400;
      color: #2e3f6a;
      margin-bottom: 5px;
      .title {
        margin-bottom: 5px;
      }
    }
    .file-title:nth-child(5) {
      margin-bottom: 10px;
    }
    .craftsman-group {
      max-height: 300px;
      overflow: hidden;
      overflow-y: scroll;
    }
  }
  .btn-group {
    padding: 20px 0;
    .cus-btn {
      width: 167px;
    }
  }
}
</style>
